<template>
    <div>
        <myTable :arr="goodsList">
            <!-- 表头 -->
            <template v-slot:header>
                <th>#</th>
                <th>商品名称</th>
                <th>价格</th>
                <th>标签</th>
                <th>操作</th>
            </template>
            <!-- 内容 -->
            <!-- <template v-slot:body="scope"> -->
            <template v-slot:body="{ row,idx }">
                <td>{{ row.id }}</td>
                <td>{{ row.goods_name }}</td>
                <td>{{ row.goods_price }}</td>
                <td>
                    <div>
                        <button v-if="!row.inputVisible" @click="showInput(row)">+Tag</button>
                        <!-- blur 表单元素失去焦点事件 -->
                        <input ref="inp" v-if="row.inputVisible" type="text"
                        v-model.trim="row.inputValue" 
                        @blur="hideInput(row)"
                        @keydown.enter="addTags(row)"
                        @keydown.esc="row.inputValue=''">
                    </div>
                    <span v-for="(item,index) in row.tags" 
                    :key="index"
                    class="badge bg-warning text-dark">{{item}}</span>
                </td>
                <td>
                    <button class="btn btn-danger btn-sm" @click="delFn(idx)">删除</button>
                </td>
            </template>
        </myTable>
    </div>
</template>

<script>
import myTable from "@/components/MyTable"
import { getList } from "@/api/tabbar.js"
/**
 * 删除功能实现
 * 1、 给删除按钮绑定点击事件，并声明事件处理函数，并传下标值传递事件处理函数
 *     1-1、表格组件通过作用域插槽把下标值传递给父组件
 * 2、在函数中，根据下标值删除数据即可
 */ 
export default {
    components: {myTable},
    data(){
        return {
            goodsList: [],
            isShow: true
        }
    },
    created(){
        getList().then(res=>{
            this.goodsList = res.data.data;
        })
    },
    methods: {
        delFn(index){
            this.goodsList.splice(index,1);
        },
        // 控制输入框的显示
        showInput(row){
            row.inputVisible = !row.inputVisible;
            this.$nextTick(()=>{
                // 输入框自动聚焦
                console.log(this.$refs.inp);
                this.$refs.inp.focus();
            })
        },
        hideInput(row){
            row.inputVisible = false;
        },
        // 新增tags
        addTags(row){
            if(!row.inputValue){
                alert("请输入内容!")
                return
            }
            row.tags.push(row.inputValue)
            row.inputValue = ""
        }
    }
}   
</script>

<style lang="less" scoped>
.badge{
    margin-right: 5px;
}
</style>